package com.SmartCare.service.impl.goodMemories;

import cn.hutool.core.bean.BeanUtil;
import com.SmartCare.common.Result;
import com.SmartCare.common.vo.goodmemories.GoodMemoriesVo;
import com.SmartCare.common.vo.goodmemories.GoodMemoryUserVo;
import com.SmartCare.mapper.goodMemories.GoodMemoriesMapper;
import com.SmartCare.pojo.goodMemories.GoodMemories;
import com.SmartCare.pojo.role.User;
import com.SmartCare.service.goodMemories.GoodMemoriesService;
import com.SmartCare.service.role.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class GoodMemoriesImpl extends ServiceImpl<GoodMemoriesMapper, GoodMemories> implements GoodMemoriesService {

    @Resource
    private GoodMemoriesMapper mapper;

    @Resource
    private UserService userService;

    @Override
    public Result saveAll(Long userId, List<String> photoUrls, String content) {
        StringBuilder stringBuilder = new StringBuilder();
        // 使用photoUrls.forEach()遍历列表，将每个url加到StringBuilder中，并在后面添加分号
        photoUrls.forEach(url -> {
            stringBuilder.append(url).append(";");
        });

        // 将StringBuilder转换为String
        String newPhotoUrls = stringBuilder.toString();

        GoodMemories one = new GoodMemories();
        one.setUserId(userId);
        one.setContent(content);
        one.setPhotoUrls(newPhotoUrls);
        boolean res = save(one);
        if (res) {
            return Result.success("保存成功");
        }
        return Result.error("保存失败");
    }

   /*  @Override
    public Result view() {
        List<Map<String, Object>> list = mapper.getUserNameAndItem();
        return Result.success(list);
    } */

    @Override
    @Transactional
    public List<String> remove(List<Long> ids) {
        List<GoodMemories> items = listByIds(ids);
        // 为未查询到结果，返回空列表
        if (items.isEmpty()) {
            return new ArrayList<>();
        }
        // 使用flatMap()将每个url拆分为多个文件名，并合并到一个Stream<String>中
        // 使用collect()将Stream<String>转换为List<String>
        List<String> fileNames = items.stream()
                .map(GoodMemories::getPhotoUrls)
                .filter(Objects::nonNull)
                .flatMap(url -> Arrays.stream(url.split(";")))
                .collect(Collectors.toList());

        removeBatchByIds(ids);
        return fileNames;
    }

    /*  @Override
     public Result getPage(String careHomeName, Integer page, Integer pageSize) {

         // 验证参数是否有效，如果无效，则返回默认值或错误信息
         if (page == null || page <= 0) {
             page = 1; // 如果 page 参数为 null 或小于等于 0，则默认设置为第一页
         }
         if (pageSize == null || pageSize <= 0) {
             pageSize = 5; // 如果 pageSize 参数为 null 或小于等于 0，则默认设置为每页 5 条数据
         }

         // 获取该养老院的所有用户id
         List<Long> ids = userService.getIdsByCHName(careHomeName);

         // 获取该养老院的所有美好瞬间记录
         QueryWrapper<GoodMemories> gqw = new QueryWrapper<>();
         gqw.in("user_id", ids);
         List<GoodMemories> memories = list(gqw);

         // 将获取到的记录根据发送时间和用户id分组为DTO，即相同发送时间和相同用户id的GoodMemories保存为一个DTO
         Map<String, List<GoodMemories>> groupedMemories = memories.stream()
                 .collect(Collectors.groupingBy(memory -> memory.getCreatedTime().toString() + "-" + memory.getUserId()));

         // 将map转为dto列表
         List<GoodMemoriesVo> dtos = new ArrayList<>();
         for (Map.Entry<String, List<GoodMemories>> entry : groupedMemories.entrySet()) {
             // 该dto包含的美好瞬间列表
             List<GoodMemories> memoriesGroup = entry.getValue();
             // 新建dto
             GoodMemoriesVo dto = new GoodMemoriesVo();
             // 获取并设置dto属性
             QueryWrapper<User> qw = new QueryWrapper<>();
             qw.eq("user_id", memoriesGroup.get(0).getUserId());
             qw.select("user_id, name, nickname, avatar_url");
             User user = userService.getOne(qw);
             GoodMemoryUserVo userVo = new GoodMemoryUserVo();
             BeanUtils.copyProperties(user,userVo);
             dto.setUserVo(userVo);
             dto.setCreateTime(memoriesGroup.get(0).getCreatedTime());
             List<String> urls = memoriesGroup.stream().map(GoodMemories::getPhotoUrl).collect(Collectors.toList());
             dto.setUrls(urls);
             List<Long> gmIds = memoriesGroup.stream().map(GoodMemories::getId).collect(Collectors.toList());
             dto.setGmIds(gmIds);
             // 添加至dto列表
             dtos.add(dto);
         }

         // 将dto按照创建时间排序
         dtos.sort(Comparator.comparing(GoodMemoriesVo::getCreateTime).reversed());

         // 计算起始索引和结束索引
         int startIndex = (page - 1) * pageSize;
         int endIndex = Math.min(startIndex + pageSize, dtos.size());

         // 计算总页数
         int totalPage = (int) Math.ceil((double) dtos.size() / pageSize);

         // 如果传入的页数超过了实际页数，返回空列表
         if (page > totalPage) {
             return Result.success(Collections.emptyList());
         }

         // 截取指定页的数据
         List<GoodMemoriesVo> pageDtos;
         try{
             pageDtos = dtos.subList(startIndex, endIndex);
         }catch (Exception e){
             throw new ServiceException(Constants.CODE_500, e.toString());
         }

         return Result.success(pageDtos);
     } */
    @Override
    public Result getPage(String careHomeName, Integer page, Integer pageSize) {

        // 获取该养老院的所有用户id
        List<Long> ids = userService.getIdsByCHName(careHomeName);


        // 获取该养老院的所有美好瞬间记录的分页数据
        QueryWrapper<GoodMemories> gqw = new QueryWrapper<>();
        gqw.in("user_id", ids);
        gqw.orderByDesc("created_time");

        IPage<GoodMemories> iPage = new Page<>(page, pageSize);
        IPage<GoodMemories> pages = page(iPage, gqw);

        // 将分页中的数据转为vo类型
        List<GoodMemories> records = pages.getRecords();
        List<GoodMemoriesVo> vos = new ArrayList<>();
        for (GoodMemories record : records) {
            // 设置vo属性
            GoodMemoriesVo vo = new GoodMemoriesVo();
            BeanUtil.copyProperties(record, vo);
            // 将urls分割成list
            if(StringUtils.isNotEmpty(record.getPhotoUrls())){
                vo.setUrls(Arrays.stream(record.getPhotoUrls().split(";")).collect(Collectors.toList()));
            }else{
                vo.setUrls(new ArrayList<>());
            }
            // 获取发送方用户
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.select("user_id, name, nickname, avatar_url");
            qw.eq("user_id", record.getUserId());
            User user = userService.getOne(qw);
            // 设置userVo
            GoodMemoryUserVo userVo = new GoodMemoryUserVo();
            BeanUtil.copyProperties(user, userVo);
            vo.setUserVo(userVo);
            // 添加至集合
            vos.add(vo);
        }

        IPage<GoodMemoriesVo> result = new Page<>();
        BeanUtil.copyProperties(pages, result);
        result.setRecords(vos);

        return Result.success(result);
    }
}
